import "./style.css";
import "vjmap3d/dist/vjmap3d.min.css";
import {
    CineonToneMapping,
} from "three";
import { createRunEnviroment, initCameraState, initEnvironment, initResConfig, setRunCameraState } from "./utils";
import { resources } from "./resources";
import { createApp } from "./app";
import { loadCarModel, loadCarRun, loadPlane } from "./models";
import { loadUI } from "./ui";

async function setupApp() {
    
    let app = createApp()
  
    app.renderer.toneMapping = CineonToneMapping;

   
    let allResources = await app.loadResources(resources, {
        showShadertoy: true,
        shadertoyMaterial: {
            uvScale: [0.5, 0.5]
        }
        // showLabel: false,
        // showHtml: true
    })
   
    // 初始化资源设置
    initResConfig(allResources);
    // 初始化相机位置
    initCameraState(app);
    // 初始化环境变化
    let startEnv = initEnvironment(app, allResources);
    // 加载车
    let car = loadCarModel(app, allResources);
   
    // 加载平面
    loadPlane(app, allResources);
    // 运动
    let run = loadCarRun(app, allResources);
    run.runCar.visible = false;
    // 运行时的环境 
    let runEnv = createRunEnviroment(app, [car.carEntity.node]);

    let state: any;
    // 启动
    const start = async () => {
        if (state) return;
        // 切换相机
        state = await setRunCameraState(app);
        app.scene.environment = runEnv.texture;

        // 替换材质
        run.runCarEntity.replaceMaterial(run.runCarMaterial)
        run.runCar.visible = true;
        
        // 车轮胎转起来
        let models = car.wheelEntity.node.children;
        car.wheelEntity.addAction(() => {
           // @ts-ignore
           models.forEach(m => {
              m.rotateZ(-8 * 0.03);
            })
        }, "WheelRotate")

    }

    // 停止 
    const stop = async () => {
        if (!state) return;
        state.cancelShake();
        state = null;
        initCameraState(app);
        app.scene.environment = startEnv.texture;

        run.runCar.visible = false
        run.runCarEntity.resetMaterial();

        // 停止车轮滚动
        car.wheelEntity.removeAction("WheelRotate");
    }

    // 加载ui
    loadUI(app, start ,stop);
}
setupApp();


